import Chan from "chanjs";

const {
  modules: {
    cms: {
      service: { Site },
    },
  },
  config: { template, env, cache},
} = Chan;

export default () => {
  return async (req, res, next) => {
    try {
      if ("domain" in req.app.locals && env === "prd" && cache) {
        await next();
        return;
      }
      let result = await Site.info();
     if(result.code === 200){
      let data = result.data
        const { domain='' } = data;
        let _template = data.template || template;
        Chan.config.template = _template;
        req.app.locals = {
          template: _template,
          domain,
          static_url: `/public/template/${_template}/`,
        };
        await next();
     }else{
        res.json(result);
     }
    } catch (error) {
      next(error);
    }
  };
};
